package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.dao.FootPersonDao;
import org.footballmanager.pandafootball.system.domain.FootPerson;
import org.footballmanager.pandafootball.system.domain.FootPersonSkill;
import org.footballmanager.pandafootball.system.form.impl.FootPersonSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootPersonMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

@Slf4j
@Service
public class FootPersonServiceImpl extends ServiceImpl<FootPerson> implements FootPersonService {

	@Autowired
    private FootPersonDao footPersonDao;
    @Autowired
    private FootPersonMapper footPersonMapper;
	@Autowired
	private FootUserPersonService footUserPersonService;
	@Autowired
	private PhotoService photoService;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private FootClubService footClubService;
    @Autowired
    private FootQdService footQdService;
    @Autowired
    private FootSkillService footSkillService;
    @Autowired
    private FootTableTitleService footTableTitleService;
    @Autowired
    private RedisService redisService;
	
	@Override
	@Transactional
	public int delete(Serializable id, HttpServletRequest request) {
		FootPerson t = this.get(id);
		log.info("删除球员:" + t.toString());
		//删除球员的实体图片
		if(t.getZp() != null){
			photoService.delete(t.getZp(), request);
		}
		return super.delete(id, request);
	}

	@Override
	public void deleteAll(HttpServletRequest request) {
	    List<FootPerson> list = footPersonDao.selectAll();
	    if(list != null && !list.isEmpty()){
	        for(FootPerson person: list){
	            super.delete(person.getId(), request);
            }
        }
	}

	//获取Excel文档的路径
	@Override
	public void getExcel(byte[] path, HttpServletRequest request) throws IOException {
		HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
		HSSFSheet sheet = wookbook.getSheetAt(0);
		int rows = sheet.getPhysicalNumberOfRows();
		Date date = new Date();
		for (int i = 1; i < rows; i++) {
			HSSFRow row = sheet.getRow(i);
			if (row == null) {
                return;
            }
            int cells = row.getPhysicalNumberOfCells();
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if(val.length <= 0) {
                return;
            }
            FootPerson fp = this.getDateById(val[0].trim());
            if(null == fp){
                fp = new FootPerson();
                fp.setId(Long.parseLong(val[0].trim()));
                this.save(this.setUpdateValue(fp, val, date), request);
            }else{
                this.updateNotNull(this.setUpdateValue(fp, val, date), request);
            }
		}
		Example example = new Example(FootPerson.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andNotEqualTo("updatetime", date);
		Example.Criteria criteria2 = example.createCriteria();
		criteria2.andIsNull("updatetime");
		example.or(criteria2);
		footPersonDao.deleteByExample(example);
	}

	private FootPerson setUpdateValue(FootPerson fp, String[] val, Date date) {
    	fp.setYw(val[1].trim());
    	fp.setName(val[2].trim());
    	//TODO 如何处理等级问题
    	fp.setDjId(Long.parseLong(val[3].trim()));
    	switch (val[3].trim()){
            case "大众/白人":
                fp.setQysj("10");
                break;
            case "普通球星":
                fp.setQysj("30");
                break;
            case "洲际球星":
                fp.setQysj("80");
                break;
            case "超级球星":
                fp.setQysj("150");
                break;
            case "顶级球星":
                fp.setQysj("250");
                break;
            default:
                break;
        }
    	fp.setUpdateTime(date);
    	return fp;
	}

	//获取Excel文档的路径
	@Override
	public void getSCardExcel(byte[] path, HttpServletRequest request) throws IOException{
		// 创建对Excel工作簿文件的引用
		HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
		// 在Excel文档中,第一张工作表的缺省索引是0
		// 其语句为:HSSFSheet sheet = wookbook.getSheet("Sheet1")
		HSSFSheet sheet = wookbook.getSheetAt(0);
		//获取到Excel文件中的所有行数
		int rows = sheet.getPhysicalNumberOfRows();
		//遍历行
		for (int i = 1; i < rows; i++) {
			// 读取左上端单元格
			HSSFRow row = sheet.getRow(i);
			// 行不为空
			if (row == null) {
                return;
            }
            //获取到Excel文件中的所有的列
            int cells = 61;
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            //将数据插入到mysql数据库中
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if(val.length <= 0) {
                return;
            }
            FootPerson fp = this.getDateById(val[0].trim());
            if(null == fp) {
                return;
            }
            this.updateNotNull(fp, request);
		}
	}

	//获取Excel文档的路径
	@Override
	public void getPCardExcel(byte[] path, HttpServletRequest request) throws IOException{
		// 创建对Excel工作簿文件的引用
		HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
		// 在Excel文档中,第一张工作表的缺省索引是0
		// 其语句为:HSSFSheet sheet = wookbook.getSheet("Sheet1")
		HSSFSheet sheet = wookbook.getSheetAt(0);
		//获取到Excel文件中的所有行数
		int rows = sheet.getPhysicalNumberOfRows();
		//遍历行
		for (int i = 1; i < rows; i++) {
			// 读取左上端单元格
			HSSFRow row = sheet.getRow(i);
			// 行不为空
			if (row == null) {
                return;
            }
            //获取到Excel文件中的所有的列
            int cells = 61;
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            //将数据插入到mysql数据库中
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if(val.length <= 0) {
                return;
            }
            FootPerson fp = this.getDateById(val[0].trim());
            if(null != fp){
                this.updateNotNull(fp, request);
            }
		}
	}

	private void processValue(StringBuilder value, int cells, HSSFRow row){
        //遍历列
        for (int j = 0; j < cells; j++) {
            //获取到列的值
            HSSFCell cell = row.getCell(j);
            if (cell != null) {
                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_FORMULA:
                        value.append(Constants.COMMA);
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        value.append(Double.valueOf(cell.getNumericCellValue()).intValue());
                        value.append(Constants.COMMA);
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        value.append(cell.getStringCellValue());
                        value.append(Constants.COMMA);
                        break;
                    default:
                        value.append(Constants.COMMA);
                        break;
                }
            }else{
                value.append(Constants.COMMA);
            }
        }
    }

	private FootPerson getDateById(String id) {
	    Example example = new Example(FootPerson.class);
	    Example.Criteria criteria = example.createCriteria();
	    criteria.andEqualTo(Constants.ID, id);
		return this.findByExample(example);
	}

	@Override
	public String findPersonByScore(String from, String to, Long userId, HttpServletRequest request) {
        Example example = new Example(FootPerson.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThanOrEqualTo("pf", from);
		if(null != to && !"".equals(to)){
		    criteria.andLessThanOrEqualTo("pf", to);
		}
		List<FootPerson> list = this.findall(example);
		if(list != null && !list.isEmpty()){
			Random rand = new Random();
			int number = rand.nextInt(list.size() - 1);
			FootPerson fp = list.get(number);
			//保存球员到用户球员表中
			footUserPersonService.saveUserPerson(userId, fp, request);
			return "".equals(fp.getName()) ? fp.getYw() : fp.getName();
		}
		return null;
	}

	@Override
	public FootPerson findByName(String name) {
		Example example = new Example(FootPerson.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", name);
		return this.findByExample(example);
	}

    /**
     * 翻页方法
     *
     * @param footPersonSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootPerson> findall(FootPersonSearchForm footPersonSearchForm) {
        List<FootPerson> list;
        if(!StringUtils.isEmpty(footPersonSearchForm.getNlName1()) || !StringUtils.isEmpty(footPersonSearchForm.getNlName2())
                || !StringUtils.isEmpty(footPersonSearchForm.getNlName3()) || !StringUtils.isEmpty(footPersonSearchForm.getNlName4())){
            list = footPersonMapper.findallWithParam(footPersonSearchForm);
            if(list != null && !list.isEmpty()){
                for(FootPerson footPerson: list){
                    footPerson.setSkillList(footPersonMapper.getSkills(footPerson.getId()));
                    footPerson.setMap(list2Map(footPerson.getSkillList()));
                }
            }
        }else{
            list = footPersonMapper.findall(footPersonSearchForm);
        }
        return list;
    }

    private Map<String, Integer> list2Map(List<FootPersonSkill> list) {
        Map<String, Integer> map = new HashMap<>();
        if (list != null) {
            for (FootPersonSkill footPersonSkill: list) {
                map.put(footPersonSkill.getYw(), footPersonSkill.getNumber());
            }
        }
        return map;
    }

    /**
     * 根据球员编码查找球员
     *
     * @param qybm 球员编码
     * @return 球员信息
     */
    @Override
    public FootPerson findByQybm(String qybm) {
        Example example = new Example(FootPerson.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qybm", qybm.trim());
        return this.findByExample(example);
    }

    /**
     * 根据主键获取记录
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootPerson get(Serializable id) {
        FootPerson person = footPersonMapper.findById(id);
        person.setSkillList(footPersonMapper.getSkills(person.getId()));
        person.setMap(list2Map(person.getSkillList()));
        return person;
    }

    /**
     * 根据等级主键获取球员列表
     *
     * @param djId 等级主键
     * @return 球员列表
     */
    @Override
    public List<FootPerson> findByDjId(Long djId) {
        return footPersonMapper.findByDjId(djId);
    }

    /**
     * 查询
     *
     * @param entityname           实体类名
     * @param map                  参数
     * @param footPersonSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootPersonSearchForm footPersonSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footPersonSearchForm);
        Page<FootPerson> page = PageHelper.startPage(footPersonSearchForm.getPageIndex(), footPersonSearchForm.getPageSize());
        List<FootPerson> list = this.findall(footPersonSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 初始化
     *
     * @param entityname 实体类名
     * @param footPersonSearchForm 条件
     * @param map                  参数
     */
    @Override
    public void init(String entityname, FootPersonSearchForm footPersonSearchForm, Model map) {
        map.addAttribute("wzList", redisService.get("listwz"));
        map.addAttribute("djList", redisService.get("listdj"));
        map.addAttribute("userList", footUserService.getall());
        map.addAttribute("gjList", redisService.get("listgj"));
        map.addAttribute("qdList", footQdService.getall());
        map.addAttribute("clubList", footClubService.getall());
        map.addAttribute("nlList", footSkillService.getall());
        map.addAttribute("head", footTableTitleService.findByTableName(Constants.PERSONTABLE));
        FootPersonSearchForm newFootPersonSearchForm = new FootPersonSearchForm();
        if(footPersonSearchForm != null){
            newFootPersonSearchForm = footPersonSearchForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, entityname), newFootPersonSearchForm);
    }

    /**
     * 删除所有
     *
     * @param footPersonSearchForm 条件
     * @param request              请求
     */
    @Override
    public void deleteAll(FootPersonSearchForm footPersonSearchForm, HttpServletRequest request) {
        if(footPersonSearchForm.getSelectIds() != null){
            String[] result = footPersonSearchForm.getSelectIds().split(Constants.COMMA);
            for(String id: result){
                this .delete(Long.parseLong(id), request);
            }
        }
    }
}
